﻿using LeederGlobal;
using SPSAndong.Business;
using SPSAndong.Comm;
using SPSAndong.Handle;
using SPSAndong.Model;
using Sunny.UI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace SPSAndong.Forms
{
    public partial class FrmAndongNew : UIPage
    {
        AutoSizeFormClass asc = new AutoSizeFormClass();
        bool isLoad = true;      //判断窗体是否首次加载
        SPSAndongHandler sPSAndongHandler;
        Dictionary<int, UIButton> DicBtnBoards = new Dictionary<int, UIButton>();
        Dictionary<int, UIButton> DicBtnVoices = new Dictionary<int, UIButton>();
        Dictionary<string, UIButton> DicBtnOthers = new Dictionary<string, UIButton>();

        public FrmAndongNew()
        {
            InitializeComponent();
        }

        private void FrmAndongNew_Load(object sender, EventArgs e)
        {

            DicBtnBoards = new Dictionary<int, UIButton>();
            DicBtnVoices = new Dictionary<int, UIButton>();
            DicBtnOthers = new Dictionary<string, UIButton>();
            asc.controllInitializeSize(this.uiPanel1);
            Init_Control();
            UpdateUI();
            GolbalVariable.SystemDeviceBag = new ConcurrentBag<SystemDeviceModel>(new SystemDeviceBLL().GetModelAll());
            if (!isLoad)
                return;
            isLoad = false;

            sPSAndongHandler = SPSAndongHandler.getInstance();
            sPSAndongHandler.OnOuttimeChanged += OuttimeChanged_Event;
            sPSAndongHandler.OnAndonDeviceStateChanged += OnAndonDeviceStateChanged;
            sPSAndongHandler.OnDeviceStateChanged += OnDeviceStateChanged_Event;
        }

        private void Init_Control()
        {
            LoadAndonDeviceAndVoice();

            DicBtnOthers.Add("PC",btnPC);
            DicBtnOthers.Add("PLC", btnPlc);
            DicBtnOthers.Add("UPS", btnUps);
            DicBtnOthers.Add("LIP", btnLIP);
            DicBtnOthers.Add("SWITCH", btnSwitch);
            DicBtnOthers.Add("CONTROL", btnControl);
            DicBtnOthers.Add("BOX1", btnIoBox1);
            DicBtnOthers.Add("BOX2", btnIoBox2);
            DicBtnOthers.Add("BOX3", btnIoBox3);

            foreach (var btnBoard in DicBtnBoards)
            {
                btnBoard.Value.Style = UIStyle.White;
                btnBoard.Value.ForeColor = Color.FromArgb(80, 160, 255);
                btnBoard.Value.RectColor = Color.FromArgb(80, 160, 255);
            }

            foreach (var btnVoice in DicBtnVoices)
            {
                btnVoice.Value.Style = UIStyle.White;
                btnVoice.Value.ForeColor = Color.FromArgb(80, 160, 255);
                btnVoice.Value.RectColor = Color.FromArgb(80, 160, 255);
            }

            foreach (var other in DicBtnOthers)
            {
                other.Value.Style = UIStyle.White;
                other.Value.ForeColor = Color.FromArgb(80, 160, 255);
                other.Value.RectColor = Color.FromArgb(80, 160, 255);
            }
   
            panelOutTime.Style = UIStyle.White;
            panelOutTime.ForeColor = Color.FromArgb(80, 160, 255);
            panelOutTime.RectColor = Color.FromArgb(80, 160, 255);
            uiPanel1.RectColor = Color.White;
        }


        /// <summary>
        /// 动态加载安东屏设备和语音设备
        /// </summary>
        private void LoadAndonDeviceAndVoice()
        {
            uiGroupBox1.Controls.Clear();
            var list = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "LED").OrderBy(x=>x.ID).ToList();
            var voicelist = GolbalVariable.VoiceAreaMusicList.OrderBy(x=>x.ID).ToList();

            var height = 25;//按钮的高度
            var jiangge = 5;//两个按钮上下之间的间隔
            var vjiangge = 80;//两个按钮左右之间的间隔
            var width = 350;//按钮的宽度
            var top = 20;//第一排按钮离顶部距离
            var left = 60;//第一列离左边的距离
            var boxWidth = Screen.PrimaryScreen.Bounds.Width - uiLine23.Location.X - 350;
            var boxheight = Screen.PrimaryScreen.Bounds.Height - 130;
            uiGroupBox1.Width = boxWidth;
            uiGroupBox1.Height = boxheight;
            if (list.Count <= 10)
            {
                width = 390;//按钮的宽度
                height = 50;//按钮的高度
                jiangge = 30;//两个按钮上下之间的间隔
                vjiangge = 80;//两个按钮左右之间的间隔
                top = 80;//第一排按钮离顶部距离
                left = 70;//第一列离左边的距离
            }
            else if (list.Count <= 15)
            {
                width = 380;//按钮的宽度
                height = 45;//按钮的高度
                jiangge = 15;//两个按钮上下之间的间隔
                vjiangge = 80;//两个按钮左右之间的间隔
                top = 50;//第一排按钮离顶部距离
                left = 80;//第一列离左边的距离
            }
            else if (list.Count <= 20)
            {

                width = 350;//按钮的宽度
                height = 38;//按钮的高度
                jiangge = 8;//两个按钮上下之间的间隔
                vjiangge = 80;//两个按钮左右之间的间隔
                top = 20;//第一排按钮离顶部距离
                left = 120;//第一列离左边的距离
                if (list.Count <= 18)
                {
                    height = 40;//按钮的高度
                    jiangge = 10;//两个按钮上下之间的间隔
                }
            }
            else if (list.Count <= 25)
            {
                width = 350;//按钮的宽度
                height = 32;//按钮的高度
                jiangge = 5;//两个按钮上下之间的间隔
                vjiangge = 80;//两个按钮左右之间的间隔
                top = 20;//第一排按钮离顶部距离
                left = 120;//第一列离左边的距离
            }

            //第一列：安安东屏
            for (int i = 0; i < list.Count; i++)
            {

                Sunny.UI.UIButton btn = new Sunny.UI.UIButton();
                btn.Name = "btnBoard" + (i + 1).ToString();
                btn.Text = list[i].DeviceName + "  " + list[i].DeviceIpAddress;
                btn.Tag = list[i].DeviceIpAddress;
                btn.Size = new Size(width, height);
                btn.Click += btn_Click;
                btn.Location = new Point(left, uiGroupBox1.Location.Y + top + (height + jiangge) * i);
                uiGroupBox1.Controls.Add(btn);
                DicBtnBoards.Add(i + 1, btn);
            }

            //第二列：语音控制器
            for (int i = 0; i < voicelist.Count; i++)
            {
                Sunny.UI.UIButton btn1 = new Sunny.UI.UIButton();
                btn1.Name = "btnVoice" + (i + 1).ToString();
                btn1.Text = voicelist[i].AreaName + "-" + "语音控制器";
                btn1.Tag = voicelist[i].IPAddress;
                btn1.Size = new Size(width, height);
                btn1.Location = new Point(left + width + vjiangge, uiGroupBox1.Location.Y + top + (height + jiangge) * i);
                uiGroupBox1.Controls.Add(btn1);
                DicBtnVoices.Add(i + 1, btn1);
            }


        }

        private void btn_Click(object sender, EventArgs e)
        {
            var btn = (UIButton)sender;

            var led = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "LED").Where(x => x.DeviceIpAddress == btn.Tag.ToString()).FirstOrDefault();
            if (led.Status==0)
            {
                UIMessageBox.Show("该安东屏通讯异常，无法执行开关屏操作，请检查网络！");
                return;
            }
            //操作单个安东屏开或关，逻辑未实现
            FrmLedOperatoin frmLedOperatoin = new FrmLedOperatoin(btn.Tag.ToString());
            frmLedOperatoin.ShowDialog();
        }

        private void UpdateUI()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                OuttimeChanged_Event();
                OnDeviceStateChanged_Event();
            }));
        }

        private void OuttimeChanged_Event()
        {
            UpdateUI_WorkOutTime();
        }

        /// <summary>
        /// 设备状态改变触发
        /// </summary>
        private void OnDeviceStateChanged_Event()
        {
            UpdateUI_DeviceCommunication();
            UpdateUI_IoCommunication();
            UpdateUI_UpsPower();
        }

        /// <summary>
        /// 主要设备通讯监控UI刷新
        /// </summary>
        private void UpdateUI_DeviceCommunication()
        {
            try
            {
                UpdateUI_Nat();
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 远程I/O通讯状态UI刷新
        /// </summary>
        private void UpdateUI_IoCommunication()
        {
            foreach (var model in GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "PLC"))
            {
                UpdateUI_IoStation(model);
            }
        }


        /// <summary>
        /// 安东屏设备状态改变触发
        /// </summary>
        private void OnAndonDeviceStateChanged()
        {
            foreach (var d in GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "LED").ToList())
            {
                //找出对应IP的button
                var btn = DicBtnBoards.FirstOrDefault(x => d.DeviceIpAddress.Equals(x.Value.Tag));
                if (!default(KeyValuePair<int, UIButton>).Equals(btn))
                {
                    switch (d.Status)
                    {
                        case 1:
                            btn.Value.ForeColor = Color.FromArgb(80, 160, 255);
                            btn.Value.RectColor = Color.FromArgb(80, 160, 255);
                            break;
                        case 0:
                            btn.Value.ForeColor = Color.Red;
                            btn.Value.RectColor = Color.Red;
                            break;
                    }
                }
            }
        }

        private void UpdateUI_Nat()
        {
            if (GolbalVariable.LipState)
            {
                //this.btnLIP.FillColor = Color.FromArgb(80, 160, 255);
                btnLIP.ForeColor = Color.FromArgb(80, 160, 255);
                btnLIP.RectColor = Color.FromArgb(80, 160, 255);
            }
            else
            {
                //this.btnLIP.FillColor = Color.Red;
                btnLIP.ForeColor = Color.Red;
                btnLIP.RectColor = Color.Red;
            }
            if (GolbalVariable.PlcState)
            {
                //this.btnPlc.FillColor = Color.FromArgb(80, 160, 255);
                btnPlc.ForeColor = Color.FromArgb(80, 160, 255);
                btnPlc.RectColor = Color.FromArgb(80, 160, 255);
            }
            else
            {
                //this.btnPlc.FillColor = Color.Red;
                btnPlc.ForeColor = Color.Red;
                btnPlc.RectColor = Color.Red;
            }
        }

        /// <summary>
        /// 更新IO箱状态
        /// </summary>
        /// <param name="systemDevice">设备对象</param>
        private void UpdateUI_IoStation(SystemDeviceModel systemDevice)
        {
            var control = this.uiPanel1.Controls.Find(systemDevice.DeviceName, true);
            if (control != null && control.Length > 0)
            {
                UIButton btn = control[0] as UIButton;
                if (systemDevice.Status == 1)
                {
                    //btn.FillColor = Color.FromArgb(80, 160, 255);
                    btn.ForeColor = Color.FromArgb(80, 160, 255);
                    btn.RectColor = Color.FromArgb(80, 160, 255);
                }
                else
                {
                    //btn.FillColor = Color.Red;
                    btn.ForeColor = Color.Red;
                    btn.RectColor = Color.Red;
                }
            }
        }

        /// <summary>
        /// 更新Ups电源状态
        /// </summary>
        /// <param name="systemDevice">设备对象</param>
        private void UpdateUI_UpsPower()
        {
            var model = GolbalVariable.UpsStatus;
            if (model == null)
                return;
            if (model.State != null && model.QueryResult)
            {
                if (model.State.UpsFault == 0)
                {
                    if (model.State.BatteryVoltage == 1)
                    {
                        //电池电压低
                        btnUps.Text = "UPS电池电压低";
                        //btnUps.FillColor = Color.Red;
                        btnUps.ForeColor = Color.Red;
                        btnUps.RectColor = Color.Red;
                    }
                    else
                    {
                        //电池正常
                        btnUps.Text = "UPS电源";
                        //btnUps.FillColor = Color.FromArgb(80, 160, 255);
                        btnUps.ForeColor = Color.FromArgb(80, 160, 255);
                        btnUps.RectColor = Color.FromArgb(80, 160, 255);
                    }
                }
                else
                {
                    //UPS故障
                    btnUps.Text = "UPS故障";
                    //btnUps.FillColor = Color.Red;
                    btnUps.ForeColor = Color.Red;
                    btnUps.RectColor = Color.Red;
                }
            }
            else
            {
                ////其他异常
                //btnUps.Text = "UPS通讯异常";
                ////btnUps.FillColor = Color.Red;
                //btnUps.ForeColor = Color.Red;
                //btnUps.RectColor = Color.Red;
            }
        }
        
        /// <summary>
        /// 更新UI
        /// </summary>
        private void UpdateUI_WorkOutTime()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                txtWorkOutTime.Text = GolbalVariable.Overtime.ToString("00");
            }));
        }

        private void FrmAndongNew_SizeChanged(object sender, EventArgs e)
        {

        }

        private void btnF_DR_Click(object sender, EventArgs e)
        {

        }

        private void btnBoard_Click(object sender, EventArgs e)
        {
            UIButton btn = sender as UIButton;
            var txts = btn.Text.Split(' ');
            var area = new int[1] { 1 };
            if (txts[0].Contains("F/DR"))
            {
                area[0] = 1;
            }
            else if (txts[0].Contains("T"))
            {
                area[0] = 2;
            }
            else if (txts[0].Contains("IP"))
            {
                area[0] = 3;
            }
            else if (txts[0].Contains("AA"))
            {
                area[0] = 4;
            }
            else
            {
                area[0] = 1;
            }
            FrmAndongBoard frmAndongBoard = new FrmAndongBoard(area, txts[0]);
            frmAndongBoard.Show();
        }

        private void btnOpenLed_Click(object sender, EventArgs e)
        {
            ShowWaitForm("正在打开安东屏，请稍候...");
            sPSAndongHandler.OpenAllLed();
            HideWaitForm();
        }

        private void btnCloseLed_Click(object sender, EventArgs e)
        {
            if (!UIMessageDialog.ShowMessageDialog("确定要关闭全部安东屏吗？", UILocalize.AskTitle, true, UIStyle.Red, true, false))
            {
                return;
            }
            ShowWaitForm("正在关闭安东屏，请稍候...");
            sPSAndongHandler.CloseAllLed();
            HideWaitForm();
        }
    }
}
